package com.android.bookgarden.ui;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.bookgarden.R;
import com.android.bookgarden.utli.AppUtils;
import com.bumptech.glide.Glide;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

import static com.tencent.connect.share.QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT;


public class ShareActivity extends Activity implements OnClickListener {
    private ImageView close, ritgh_icon;
    private TextView title, ritgh_text;
    private ImageView codeImg;
    private int QR_WIDTH = 150, QR_HEIGHT = 150;
    private String shereImgPath;
    Tencent mTencent;
    private IWXAPI wxApi;
    private LinearLayout layout[] = new LinearLayout[4];
    private int[] layoutId = {R.id.shereQQ, R.id.shereQZno, R.id.shereWx, R.id.shereWxF};
    private String Tag = "ShareActivity";
    public static ShareActivity shareActivity;
    private String unifiedShareTitle="邻家学院";
    private String unifiedShareDescription="邻家需要，学无止境哦";
    private String unifiedShareIconUrl="http://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1546192586167&di=7f56f5355d4f1628c1e144e1d7d706db&imgtype=jpg&src=http%3A%2F%2Fimg1.imgtn.bdimg.com%2Fit%2Fu%3D2528534191%2C265036737%26fm%3D214%26gp%3D0.jpg";
    private String unifiedShareUrl="https://www.baidu.com/";
    final Bitmap[] thumb = {null};
    private int chooseChannel = 0;
    private LinearLayout ll_container;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_share);

        initView();
        // 实例化
        wxApi = WXAPIFactory.createWXAPI(this, "wx153a5225a71797fb");
        wxApi.registerApp("wx153a5225a71797fb");
        mTencent = Tencent.createInstance("101531077", ShareActivity.this);
        shareActivity = this;
    }


    private void initView() {
        findViewById(R.id.ll_container).setOnClickListener(this);
        findViewById(R.id.shereWx).setOnClickListener(this);
        findViewById(R.id.shereWxF).setOnClickListener(this);
        findViewById(R.id.shereQQ).setOnClickListener(this);
        findViewById(R.id.shereQZno).setOnClickListener(this);
        TextView tv_cancel = (TextView) findViewById(R.id.tv_cancel);
        ll_container = (LinearLayout) findViewById(R.id.ll_container);
        ll_container.setOnClickListener(this);
        tv_cancel.setOnClickListener(this);
    }


    IUiListener qZoneShareListener = new IUiListener() {
        @Override
        public void onError(UiError e) {
            Toast.makeText(getApplicationContext(), "分享失败", Toast.LENGTH_SHORT).show();
            finish();
        }

        @Override
        public void onCancel() {
            // showResult("onCancel", "");
//            Toast.makeText(getApplicationContext(), "取消分享", Toast.LENGTH_SHORT).show();
            finish();
        }

        @Override
        public void onComplete(Object arg0) {
            Toast.makeText(getApplicationContext(), "分享成功", Toast.LENGTH_SHORT).show();


        }

    };

    // /**
    // * 微信分享 （这里仅提供一个分享网页的示例，其它请参看官网示例代码）
    // *
    // * @param flag
    // * (0:分享到微信好友，1：分享到微信朋友圈)
    // */
    private void wechatShare(final int flag) {
        if (!AppUtils.isInstallApk(this, "com.tencent.mm")) {
           Toast.makeText(this, "请先安装微信！", Toast.LENGTH_SHORT).show();
            return;
        }
        System.out.println("微信能分享吗");
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = unifiedShareUrl;
        final WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = unifiedShareTitle;
        msg.description = unifiedShareDescription;
        new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        try {
                            if (!TextUtils.isEmpty(unifiedShareIconUrl)) {
                                thumb[0] = Glide.with(ShareActivity.this).load(unifiedShareIconUrl).asBitmap().centerCrop().into(80, 80).get();
                            }
                            if (null != thumb[0]) {
                                // 生成一张缩略图，注意：此处的bitmap千万不能太大，不要超过40k,否则sendReq()时，会有可能返回false。
                                Bitmap thumbBmp = Bitmap.createScaledBitmap(thumb[0], 80, 80, true);
                                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                thumbBmp.compress(Bitmap.CompressFormat.PNG, 70, baos);
                                msg.thumbData = baos.toByteArray();
                            }

                            SendMessageToWX.Req req = new SendMessageToWX.Req();
                            req.transaction = String.valueOf(System.currentTimeMillis());
                            req.message = msg;
                            req.scene = flag == 0 ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;
                            Boolean fla = wxApi.sendReq(req);
                        } catch (InterruptedException e) {
                        } catch (ExecutionException e) {
                        }
                    }
                }
        ).start();
    }


    private void noShow() {
//        if (null != sherePop && sherePop.isShowing()) {
//            sherePop.dismiss();
//        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Tencent.onActivityResultData(requestCode, resultCode, data, qZoneShareListener);
        if (requestCode == com.tencent.connect.common.Constants.REQUEST_API) {
            if (resultCode == com.tencent.connect.common.Constants.REQUEST_QQ_SHARE || resultCode == com.tencent.connect.common.Constants.REQUEST_QZONE_SHARE || resultCode == com.tencent.connect.common.Constants.REQUEST_OLD_SHARE) {
                Tencent.handleResultData(data, qZoneShareListener);
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.shereQQ:
                shareQQ();
                chooseChannel = 2;
                noShow();
                break;
            case R.id.shereQZno:
                shareToQzone();
                chooseChannel = 3;
                noShow();
                break;
            case R.id.shereWx:
                wechatShare(0);
                chooseChannel = 0;
                noShow();
                ShareActivity.this.finish();
                break;
            case R.id.shereWxF:
                wechatShare(1);
                chooseChannel = 1;
                noShow();
                ShareActivity.this.finish();
                break;
            case R.id.tv_cancel:
                finish();
                break;
            case R.id.ll_container:
                finish();
                break;
            default:
                break;
        }
    }

    private void shareQQ() {
        final Bundle params = new Bundle();
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        params.putString(QQShare.SHARE_TO_QQ_TITLE, unifiedShareTitle);
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, unifiedShareDescription);
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, unifiedShareUrl);
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, unifiedShareIconUrl);
        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "贵州通");
        mTencent.shareToQQ(ShareActivity.this, params, qZoneShareListener);
    }

    private void shareToQzone() {//分享类型
        Bundle bundle = new Bundle();
        bundle.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE,
                SHARE_TO_QZONE_TYPE_IMAGE_TEXT);// 类型
        bundle.putString(QzoneShare.SHARE_TO_QQ_TITLE, unifiedShareTitle);// 标题
        bundle.putString(QzoneShare.SHARE_TO_QQ_SUMMARY,
                unifiedShareDescription);// 概要
        bundle.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL,
                unifiedShareUrl);

        bundle.putString(QzoneShare.SHARE_TO_QQ_IMAGE_URL, unifiedShareIconUrl);//图标
//        // 下面这个必须加上 不然无法调动 qq空间
        ArrayList<String> imageUrls = new ArrayList<String>();

        imageUrls.add(unifiedShareIconUrl);
        bundle.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, imageUrls);
        mTencent.shareToQzone(ShareActivity.this, bundle, qZoneShareListener);
    }

    public void notifaiShere(int sates) {
        String s = String.valueOf(sates);
        if (s.equals("0") || s.equals("1")) {
            finish();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        shareActivity = null;
    }
}


